//
//  ClockSettingView.swift
//  Kosspot
//
//  Created by 李鑫 on 2025/7/14.
//

import SwiftUI
import UTEBluetoothRYApi

struct ClockSettingView: View {
    @EnvironmentObject var appState: AppState
    @StateObject var viewModel = DeviceDetailVM()
    @Binding var alarm : UTEModelClock
    @State var isEdit : Bool
    @State private var alarms:[UTEModelClock] = []
    @State private var cycleTypes: [UTEWeekType] = []
    @State private var selectedTime = Date()
    @State var isMon:Bool = false
    @State var isTue:Bool = false
    @State var isWen:Bool = false
    @State var isThur:Bool = false
    @State var isFri:Bool = false
    @State var isSat:Bool = false
    @State var isSun:Bool = false

    var body: some View {
        VStack {
            CustomNavigationBar(rightImageName:nil, title: "设置闹钟") {}
            ScrollView (.vertical,showsIndicators: false){
                ZStack(alignment: .center) {
                    DatePicker("",
                               selection: $selectedTime,
                               displayedComponents: [.hourAndMinute])
                    .datePickerStyle(.wheel)
                    .labelsHidden()
                    .cornerRadius(10)
                    .font(.system(size: 20))
                    .environment(\.colorScheme, .dark)
                    .padding(.horizontal,28)
                }
                .frame(height: 226)
                .background(Color(hex: "#1E1E1E"))
                .cornerRadius(16)
                .padding(.horizontal,12)
                
                HStack {
                    Text("重复").font(.system(size: 16)).foregroundStyle(.white)
                    Spacer()
                }
                .frame(height: 44)
                .background(.clear)
                .padding(.horizontal,12)
                
                
                VStack(alignment: .leading,spacing: 12) {
                    // 星期选择器
                    HStack(spacing: 20) {
                        Button(action: {
                            isMon.toggle()
                            if isMon {
                                cycleTypes.append(.UTEWeekTypeMon)
                            }else {
                                if let index = cycleTypes.firstIndex(of: .UTEWeekTypeMon) {
                                    cycleTypes.remove(at: index)
                                }
                            }
                        }) {
                            Text("周一")
                                .frame(width: 60, height: 30)
                                .background(.clear)
                                .foregroundColor(isMon ? Color(hex: "#00E9DA") : .white)
                                .cornerRadius(15)
                                .overlay(
                                    RoundedRectangle(cornerRadius:15)
                                        .stroke(isMon ? Color(hex: "#00E9DA") : .white, lineWidth: 0.5)
                                )
                        }
                        
                        
                        Button(action: {
                            isTue.toggle()
                            if isTue {
                                cycleTypes.append(.UTEWeekTypeTue)
                            }else {
                                if let index = cycleTypes.firstIndex(of: .UTEWeekTypeTue) {
                                    cycleTypes.remove(at: index)
                                }
                            }
                        }) {
                            Text("周二")
                                .frame(width: 60, height: 30)
                                .background(.clear)
                                .foregroundColor(isTue ? Color(hex: "#00E9DA") : .white)
                                .cornerRadius(15)
                                .overlay(
                                    RoundedRectangle(cornerRadius:15)
                                        .stroke(isTue ? Color(hex: "#00E9DA") : .white, lineWidth: 0.5)
                                )
                        }
                        
                        Button(action: {
                            isWen.toggle()
                            if isWen {
                                cycleTypes.append(.UTEWeekTypeWed)
                            }else {
                                if let index = cycleTypes.firstIndex(of: .UTEWeekTypeWed) {
                                    cycleTypes.remove(at: index)
                                }
                            }
                        }) {
                            Text("周三")
                                .frame(width: 60, height: 30)
                                .background(.clear)
                                .foregroundColor(isWen ? Color(hex: "#00E9DA") : .white)
                                .cornerRadius(15)
                                .overlay(
                                    RoundedRectangle(cornerRadius:15)
                                        .stroke(isWen ? Color(hex: "#00E9DA") : .white, lineWidth: 0.5)
                                )
                        }
                        Button(action: {
                            isThur.toggle()
                            if isThur {
                                cycleTypes.append(.UTEWeekTypeThur)
                            }else {
                                if let index = cycleTypes.firstIndex(of: .UTEWeekTypeThur) {
                                    cycleTypes.remove(at: index)
                                }
                            }
                        }) {
                            Text("周四")
                                .frame(width: 60, height: 30)
                                .background(.clear)
                                .foregroundColor(isThur ? Color(hex: "#00E9DA") : .white)
                                .cornerRadius(15)
                                .overlay(
                                    RoundedRectangle(cornerRadius:15)
                                        .stroke(isThur ? Color(hex: "#00E9DA") : .white, lineWidth: 0.5)
                                )
                        }
                    }.padding(.leading,20)
                    HStack(spacing: 20) {
                        Button(action: {
                            isFri.toggle()
                            if isFri {
                                cycleTypes.append(.UTEWeekTypeFri)
                            }else {
                                if let index = cycleTypes.firstIndex(of: .UTEWeekTypeFri) {
                                    cycleTypes.remove(at: index)
                                }
                            }
                        }) {
                            Text("周五")
                                .frame(width: 60, height: 30)
                                .background(.clear)
                                .foregroundColor(isFri ? Color(hex: "#00E9DA") : .white)
                                .cornerRadius(15)
                                .overlay(
                                    RoundedRectangle(cornerRadius:15)
                                        .stroke(isFri ? Color(hex: "#00E9DA") : .white, lineWidth: 0.5)
                                )
                        }
                        
                        
                        Button(action: {
                            isSat.toggle()
                            if isSat {
                                cycleTypes.append(.UTEWeekTypeSat)
                            }else {
                                if let index = cycleTypes.firstIndex(of: .UTEWeekTypeSat) {
                                    cycleTypes.remove(at: index)
                                }
                            }
                        }) {
                            Text("周六")
                                .frame(width: 60, height: 30)
                                .background(.clear)
                                .foregroundColor(isSat ? Color(hex: "#00E9DA") : .white)
                                .cornerRadius(15)
                                .overlay(
                                    RoundedRectangle(cornerRadius:15)
                                        .stroke(isSat ? Color(hex: "#00E9DA") : .white, lineWidth: 0.5)
                                )
                        }
                        
                        Button(action: {
                            isSun.toggle()
                            if isSun {
                                cycleTypes.append(.UTEWeekTypeSun)
                            }else {
                                if let index = cycleTypes.firstIndex(of: .UTEWeekTypeSun) {
                                    cycleTypes.remove(at: index)
                                }
                            }
                        }) {
                            Text("周日")
                                .frame(width: 60, height: 30)
                                .background(.clear)
                                .foregroundColor(isSun ? Color(hex: "#00E9DA") : .white)
                                .cornerRadius(15)
                                .overlay(
                                    RoundedRectangle(cornerRadius:15)
                                        .stroke(isSun ? Color(hex: "#00E9DA") : .white, lineWidth: 0.5)
                                )
                        }
                        Spacer()
                    }.padding(.leading,20)
                }
                .frame(height: 112)
                .background(Color(hex: "#1E1E1E"))
                .cornerRadius(16)
                .padding(.horizontal,12)
                Spacer().frame(height: 12)
                HStack {
                    Text("无法在当前时间后的2分钟内设置新闹钟").font(.system(size: 14)).foregroundStyle(Color(hex: "#B2B2B2"))
                    Spacer()
                }
                .padding(.horizontal,12)
                Spacer()
            }
            HStack {
                Button {
                    print(cycleTypes)
                    getHourAndMinutes()
                    alarm.name = "闹钟\(alarm.index)"
                    alarm.cycle = Int32(cycleTypes.map { $0.rawValue }.reduce(0) { $0 | $1 })
                    alarm.enable = true
                    alarms.append(alarm)
                    viewModel.setAlarmArrayModel(alarms: alarms) {success, data in
                        if success {
                                print("设置成功：\(data ?? [:])")
                            viewModel.getAlarmArray()
                            appState.navigateBack()
                            } else {
                                print("失败原因：\(data ?? [:])")
                            }
                    }
                } label: {
                    Text("保存")
                        .font(.system(size: 16))
                        .foregroundStyle(Color(hex: "#242424"))
                }
            }
            .frame(maxWidth: .infinity, alignment: .center)
            .frame(height: 44)
            .gradientBackground(colors: [Color(hex: "#00F3AF"),Color(hex: "#00E9DA")], type: .linear(start: .leading, end: .trailing), cornerRadius: 22.0)
            .padding(.horizontal,12)
            .padding(.bottom,20)
        }
        .navigationBarHidden(true)
        .background(Color(hex: "#0A0A0A"))
        .edgesIgnoringSafeArea(.all)
        .onAppear {
            if isEdit {
                initpargarm()
            }
        }
    }

    func initpargarm() {
        let cycle = UTEWeekType.getWeekdayName(from: Int(alarm.cycle))
        print(cycle)
        cycle.forEach { day in
            switch day {
            case "周一":
                isMon = true
                cycleTypes.append(.UTEWeekTypeMon)
            case "周二":
                isTue = true
                cycleTypes.append(.UTEWeekTypeTue)
            case "周三":
                isWen = true
                cycleTypes.append(.UTEWeekTypeWed)
            case "周四":
                isThur = true
                cycleTypes.append(.UTEWeekTypeThur)
            case "周五":
                isFri = true
                cycleTypes.append(.UTEWeekTypeFri)
            case "周六":
                isSat = true
                cycleTypes.append(.UTEWeekTypeSat)
            case "周日":
                isSun = true
                cycleTypes.append(.UTEWeekTypeSun)
            default: break
            }
        }
        selectedTime = TimestampHelper.convertHourM("\(alarm.timeHour):\(alarm.timeMin)") ?? Date()
    }
    
    
    func getHourAndMinutes() {
        let formatter = DateFormatter()
        formatter.dateStyle = .none
        formatter.timeStyle = .short
        _ = formatter.string(from: selectedTime)
        let components = Calendar.current.dateComponents([.hour, .minute], from: selectedTime)
        _ = components.hour ?? 0
        _ = components.minute ?? 0
        alarm.timeHour = components.hour ?? 0
        alarm.timeMin = components.minute ?? 0
    }
}

//#Preview {
//    ClockSettingView()
//}



